package com.zy.chat.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.zy.chat.dto.LoginFormDTO;
import com.zy.chat.util.UserHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.data.redis.core.RedisTemplate;
import static com.zy.chat.util.RedisContants.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @author zy
 * @date 2023/5/15 20:03
 */

@Component
public class RefreshInceteptor implements HandlerInterceptor {



    private RedisTemplate redisTemplate;
    public RefreshInceteptor(RedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        // 判断用户是否已登录，未登录则重定向到登录页面
      if(StrUtil.isBlank(token)){
          return true;
      }

        Map userMap = redisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        if (userMap==null){
            return true;
        }
        LoginFormDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new LoginFormDTO(), false);
        UserHolder.setUserHolder(userDTO);
        redisTemplate.expire(LOGIN_USER_KEY + token,LOGIN_USER_TTL, TimeUnit.HOURS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
